<?php

namespace App\Http\Controllers\Admin;

use App\Models\BookList;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class BookListController extends BaseController
{
    public function __construct()
    {
        parent::__construct();
        $this->middleware('check_admin_login');
    }

    public function index(Request $request)
    {
        $page                         = intval($request->get('page',1));
        $page                         = max($page ,1);
        $page_size                    = intval($request->get('limit',10));

        $builder = BookList::query()->with('books')->where('deleted',0);

        $columns = ['id','title','list_image','is_homepage','detail_image','sort','created_at'];
        $list = $builder->orderBy('sort','asc')->paginate($page_size,$columns,'page',$page);
        //dd($list);
        //die;
        $items = [];
        if(!empty($list->items()))
        {
            foreach ($list->items() as $item)
            {
                $items[] = [
                    'id'           => $item->id,
                    'title'        => $item->title,
                    'list_image'   => $item->list_image,
                    'is_homepage'  => $item->is_homepage,
                    'detail_image' => $item->detail_image,
                    'sort'         => $item->sort,
                    'created_at'   => date('Y-m-d H:i:s',$item->created_at),
                    'book_num'     => count($item->books)
                ];
            }
        }

        $data = [
            '_meta' => [
                'total_count'  => $list->total(),
                'page_count'   => $list->lastPage(),
                'current_page' => $list->currentPage(),
                'per_page'     => $list->perPage()
            ],
            "items" => $items
        ];

        return $this->res([
            'data' => $data
        ]);
    }

    public function store(Request $request)
    {
        $title        = trim($request->get('title'));
        $list_image   = trim($request->get('list_image'));
        $detail_image = trim($request->get('detail_image'));
        $is_homepage  = intval($request->get('is_homepage',1));
        $sort         = intval($request->get('sort'));
        $books        = trim($request->get('books'));   // [{"book_id":5,"message":"推荐语"},{"book_id":6,"message":"推荐语2"}]

        if(empty($title) || empty($list_image) || empty($detail_image))
        {
            return $this->err(1,200,'','参数错误');
        }

        $data = [
            'title'       => $title,
            'list_image'  => $list_image,
            'detail_image'=> $detail_image,
            'is_homepage' => $is_homepage,
            'sort'        => $sort,
            'created_at'  => $this->time,
            'updated_at'  => $this->time
        ];

        $attach = [];
        if(!empty($books))
        {
            $books_arr = json_decode($books,true);
            foreach ($books_arr as $v)
            {
                $attach[$v['book_id']] = ['message' => $v['message']];
            }
        }

        //dd($attach);
        $book_list = BookList::create($data);
        if(!empty($attach))
        {
            $book_list->books()->attach($attach);
        }
        return $this->ok([],'添加成功');
    }

    public function update(Request $request)
    {
        $id           = intval($request->get('id'));
        $title        = trim($request->get('title'));
        $list_image   = trim($request->get('list_image'));
        $detail_image = trim($request->get('detail_image'));
        $is_homepage  = intval($request->get('is_homepage',1));
        $sort         = intval($request->get('sort'));
        $books        = trim($request->get('books'));   // [{"book_id":5,"message":"推荐语"},{"book_id":6,"message":"推荐语2"}]

        if(empty($id) || empty($title) || empty($list_image) || empty($detail_image))
        {
            return $this->err(1,200,'','参数错误');
        }

        $book_list = $this->_check_info($id);
        if(empty($book_list))
        {
            return $this->err(1,200,'','书单不存在');
        }


        $data = [
            'title'       => $title,
            'list_image'  => $list_image,
            'detail_image'=> $detail_image,
            'is_homepage' => $is_homepage,
            'sort'        => $sort,
            'updated_at'  => $this->time
        ];

        $book_list->update($data);

        $attach = [];
        if(!empty($books))
        {
            $books_arr = json_decode($books,true);
            foreach ($books_arr as $v)
            {
                $attach[$v['book_id']] = ['message' => $v['message']];
            }
        }

        if(!empty($attach))
        {
            $book_list->books()->sync($attach);
        }
        else
        {
            $book_list->books()->detach();
        }
        return $this->ok([],'修改成功');
    }

    private function _check_info($id)
    {
        $book_list = BookList::query()->where('id',$id)->where('deleted',0)->first();
        return $book_list;
    }

    public function show(Request $request)
    {
        $id = intval($request->get('id'));
        if(empty($id))
        {
            return $this->err(1,200,'','参数错误');
        }

        $book_list = BookList::query()->with('books')->where('id',$id)->where('deleted',0)->first();
        if(empty($book_list))
        {
            return $this->err(1,200,'','书单不存在');
        }

        $items = [];
        //dd($book_list->books);
        if(!empty($book_list->books))
        {
            foreach ($book_list->books as $v)
            {
                $items[] = [
                    'book_id'           => $v->id,
                    'image'             => $v->image,
                    'title'             => $v->title,
                    'author'            => $v->author,
                    'message'           => $v->pivot->message,
                ];
            }
        }

        //dd($book_list);

        $result = [
            'id'           => $id,
            'title'        => $book_list->title,
            'list_image'   => $book_list->list_image,
            'detail_image' => $book_list->detail_image,
            'is_homepage'  => $book_list->is_homepage,
            'sort'         => $book_list->sort,
            'items'        => $items,
        ];

        return $this->ok($result);
    }

    public function destroy(Request $request)
    {
        $id = intval($request->get('id'));
        if(empty($id))
        {
            return $this->err(1,200,'','参数错误');
        }

        $book_list = $this->_check_info($id);
        if(empty($book_list))
        {
            return $this->err(1,200,'','书单不存在');
        }

        if(!$book_list->deleted)
        {
            $book_list->update([
                'deleted'      => 1,
                'deleted_at'   => $this->time
            ]);
            return $this->ok([],'删除成功');
        }

        return $this->err(1,200,'','删除失败');
    }

    public function setTopImage(Request $request)
    {
        $top_image = trim($request->get('top_image'));
        if(empty($top_image))
        {
            return $this->err(1,200,'','参数错误');
        }

        $ret = \Redis::set('book-shop:book-list:top-image',$top_image);
        return $this->ok([],'保存成功');
    }

    public function getTopImage()
    {
        $top_image = \Redis::get('book-shop:book-list:top-image');
        $top_image = $top_image ? $top_image : '';

        $result = [
            'top_image' => $top_image
        ];
        return $this->ok($result);
    }
}
